﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;

namespace Kiosk
{
    /// <summary>
    /// Interaction logic for Pathways.xaml
    /// </summary>
    public partial class Pathways : Window
    {
        #region Pathways window variables
        /// <summary>
        /// A List to hold Pathway objects constructed from the SQL query results 
        /// </summary>
        List<Pathway> listPathways = new List<Pathway>();

        /// <summary>
        /// A DataSet to hold the SQL query results
        /// </summary>
        private DataSet dsPathways = new DataSet();

        /// <summary>
        /// Saves the number of results returned by the SQL query
        /// </summary>
        private int returnCount = 0;
        #endregion

        /// <summary>
        /// Instantiates the Pathway window
        /// </summary>
        public Pathways()
        {
            InitializeComponent();
        }

        #region Pathways window event handlers
        /// <summary>
        /// Handles clicks of the individual pathway buttons
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPath_Click(object sender, RoutedEventArgs e)
        {
            //cast the sender as a button
            Button b = (Button)sender;

            //buttons are named "pathway_#", so split the name to get the number
            string[] strBtnName = b.Name.Split('_');
            
            //parse the number for modulus operation later
            int iBtnNumber = Convert.ToInt32(strBtnName[2]);

            //check the selected pathways list to see if it's already selected
            if (sGlobals.selectedPathwayID.Exists(element => element == strBtnName[1]))
            {
                //if already selected, deselect
                sGlobals.selectedPathwayID.Remove(strBtnName[1]);

                //update the UI--use green or yellow style as appropriate
                if (iBtnNumber % 2 == 0)
                    b.Style = (Style)FindResource("btnCatYellow");
                else
                    b.Style = (Style)FindResource("btnCatGreen");
            }
            else
            {
                //add the pathway id to the selected pathways list
                sGlobals.selectedPathwayID.Add(strBtnName[1]);

                //update the UI--green or yellow style as appropriate
                if (iBtnNumber % 2 == 0)
                    b.Style = (Style)FindResource("btnCatYellowDown");
                else
                    b.Style = (Style)FindResource("btnCatGreenDown");

                lblError.Visibility = Visibility.Hidden;
            }
        }

        /// <summary>
        /// Logs the user out when "Logout" is clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            sGlobals.logout();
        }

        /// <summary>
        /// Takes the user back to the Focused Areas of Study screen when "Back" is clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            sGlobals.selectedPathwayID.Clear();
            sGlobals.focusedAreasOfStudy.Show();
            this.Hide();
        }

        /// <summary>
        /// Handles the click event for the submit button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            //if the user has selected at least one pathway, go to BrowseMentors
            if (sGlobals.selectedPathwayID.Count > 0)
            {
                DataSet dsMentors = new DataSet();
                int returnCount = 0;
                string whereParams = "";

                if (sGlobals.selectedPathwayID.Count > 0)
                {
                    whereParams = "WHERE mentor.pathway_id = " + string.Join(" OR mentor.pathway_id = ", sGlobals.selectedPathwayID) + " AND mentor.deletion_date IS NULL";
                }

                string sql = "SELECT mentor_id, CONCAT_WS(' ',first_name, last_name) AS fullname, degree_name, pathway_name, mentor_id, photo FROM mentor " +
                               "LEFT JOIN lkup_pathway ON mentor.pathway_id = lkup_pathway.pathway_id " +
                               "LEFT JOIN lkup_degree ON mentor.degree = lkup_degree.degree_id " +
                                whereParams;
                try
                {
                    dsMentors = sGlobals.dbWrapper.ExecuteSQLStatement(sql, ref returnCount);
                    if (returnCount > 0)
                    {
                        sGlobals.browseMentors.previousPage = sGlobals.pathways;
                        sGlobals.browseMentors.Show();
                        this.Hide();
                    }
                    else
                    {
                        WarningMessage warning = new WarningMessage();
                        warning.lblMessage.Content = "There are no mentors for the specified pathway(s).";
                        warning.ShowDialog();
                    }
                }
                catch (Exception ex)
                {
                    if (!sGlobals.hasLogout)
                    {
                        WarningMessage warning = new WarningMessage();
                        warning.lblMessage.Content = "There was a problem loading the page.\r\nIf the problem persists, please contact your system administrator";
                        warning.ShowDialog();
                    }
                }

            }
            //otherwise, display an error message
            else
            {
                lblError.Visibility = Visibility.Visible;
            }
        }

        /// <summary>
        /// Handles the IsVisibleChanged event, so it runs whenever the window is shown
        /// or hidden. This allows the display to refresh properly based on the values
        /// in sGlobals.selectedAOSID (if this code only appeared in the Window ctor the
        /// values selected on the Focused Areas of Study page would not be used
        /// to the SQL query).
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
            {
                //clear out the window's previous contents and results
                listPathways.Clear();
                dsPathways.Clear();
                returnCount = 0;
                grPathways.Children.Clear();
                grPathways.RowDefinitions.Clear();
                string sql;
                //construct the sql where clause based on the values in the
                //selectedAOSID list          
                if (sGlobals.selectedAOSID.Count > 0)
                {
                    string strWhereClause = string.Join("','", sGlobals.selectedAOSID);

                    //create sql query
                    sql = "SELECT pathway_id, focus_id, pathway_name FROM lkup_pathway" +
                        " WHERE focus_id IN('" + strWhereClause + "')";
                }
                else
                {
                    sql = "SELECT pathway_id, focus_id, pathway_name FROM lkup_pathway";
                }

                try
                {
                    //query database
                    dsPathways = sGlobals.dbWrapper.ExecuteSQLStatement(sql, ref returnCount);
                }
                catch (Exception ex)
                {
                    if (!sGlobals.hasLogout)
                    {
                        WarningMessage warning = new WarningMessage();
                        warning.lblMessage.Content = "There was a problem loading the page.\r\nIf the problem persists, please contact your system administrator";
                        warning.ShowDialog();
                    }
                }
                //get results
                if (returnCount > 0)
                {
                    for (int i = 0; i < returnCount; i++)
                    {
                        //add a Pathway object to the list for each Pathway returned by query
                        listPathways.Add(new Pathway(
                            dsPathways.Tables[0].Rows[i]["pathway_name"].ToString(),
                            Int32.Parse(dsPathways.Tables[0].Rows[i]["pathway_id"].ToString()),
                            Int32.Parse(dsPathways.Tables[0].Rows[i]["focus_id"].ToString())
                            ));
                    }
                }

                //create a button with the appropriate style for each pathway and add it to the Grid
                for (int i = 0; i < listPathways.Count; i++)
                {
                    Button btnPath = new Button();

                    //causes the Button's content to use text wrapping if necessary
                    btnPath.Content = new TextBlock { Text = listPathways[i].Name, TextWrapping = TextWrapping.Wrap, TextAlignment = TextAlignment.Center };
                    
                    //name each button based on the Pathway's Id
                    btnPath.Name = String.Format("pathway_{0}_{1}",listPathways[i].Id.ToString(), i);
                    
                    //alternate green and yellow style for every other button
                    string strStyle = (i % 2 == 0) ? "btnCatYellow" : "btnCatGreen";

                    //if the user is returning to the Pathways window from the BrowseMentor
                    //window, this line makes sure previously selected pathways will be
                    //indicated as such by the UI by checking the global pathway list
                    //to see if the pathway that is currently being added to the UI should
                    //be displayed as "selected"
                    if(sGlobals.selectedPathwayID.Exists(element => element == listPathways[i].Id.ToString()))
                        strStyle += "Down";

                    //add the style we just figured out to this button
                    btnPath.Style = (Style)FindResource(strStyle);
                    btnPath.Margin = new Thickness(10);
                    btnPath.MaxHeight = 40;

                    //point this button's click event listener to the correct handler
                    btnPath.Click += new RoutedEventHandler(btnPath_Click);

                    //after every third button added, add a new row
                    if (i % 3 == 0)
                    {
                        grPathways.RowDefinitions.Add(new RowDefinition());
                        grPathways.RowDefinitions[grPathways.RowDefinitions.Count - 1].MaxHeight = 120;

                    }

                    //add the button to the Grid, and set its row and column
                    grPathways.Children.Add(btnPath);
                    Grid.SetRow(btnPath, grPathways.RowDefinitions.Count - 1);
                    Grid.SetColumn(btnPath, i % 3);
                }
            }
        }
        #endregion
    }
}
